<template>
	<view class="wrap" :class="size || normal" @tap='show = !show'>
		<u-icon name="plus" :size="iconSize" color="#BCC7D8" />
		<u-action-sheet :list="list" v-model="show" :safe-area-inset-bottom="true" @click="clickActionSheet"></u-action-sheet>
	</view>
</template>

<script>
	export default {
		props: ['size', 'maxCount'],
		data() {
			return {
				show: false,
				list: [
					{ text: '拍照' },
					{ text: '从相册中选择' }
				],
			}
		},
		computed: {
			iconSize() {
				if (this.size === 'large') {
					return 50;
				}
				if (this.size === 'mini') {
					return 30;
				}
				return 40;
			}
		},
		methods: {
			clickActionSheet(e) {
				e == 0 ? this.captureImage() : this.chooseImage()
			},
			
			// 5+拍照
			captureImage() {
				var cmr = plus.camera.getCamera();
				var res = cmr.supportedImageResolutions[0];
				var fmt = cmr.supportedImageFormats[0];
				console.log("Resolution: "+res+", Format: "+fmt);
				cmr.captureImage( path => {
						// path为字符串
						this.compressImage(path);
					},
					error => {
						// plus.nativeUI.toast( "Capture image failed: " + error.message );
					},
					{ resolution:res, format:fmt }
				);
			},
			
			// 5+相册
			chooseImage() {
				plus.gallery.pick(path => {
					// path为{"files": [src1,src2]}
					path.files.forEach(ele => {
						this.compressImage(ele);
					})
				}, error => {
					// plus.nativeUI.toast( "Choose image failed: " + error.message );
				}, {
					filter: 'image',
					multiple: true,
					maximum: this.maxCount || 3,
					onmaxed: () => {
						plus.nativeUI.toast(`最多选择${this.maxCount}张图片`);
					}
				})
			},
			
			// 5+压缩图片质量
			compressImage(url) {
				var picName = new Date().getTime();
				plus.zip.compressImage({
						src: url,
						dst: `_doc/${picName}.jpg`,
						quality: 50
					}, res => {
						console.log(res);
						this.$emit('choose', res.target);
					}, error => {
						console.log(error.message);
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap {
		background-color: #F6F8FB;
		text-align: center;
	}
	.large {
		width: 300rpx;
		height: 300rpx;
		line-height: 330rpx;
	},
	.normal {
		width: 156rpx;
		height: 156rpx;
		line-height: 176rpx;
	},
	.mini {
		width: 100rpx;
		height: 100rpx;
		line-height: 110rpx;
	}
</style>
